package com.chen.servicemap.remote;

import com.alibaba.fastjson2.JSONObject;
import com.chen.internalcommon.constant.MapConfigConstants;
import com.chen.internalcommon.dto.ResponseResult;
import com.chen.internalcommon.response.TrackResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @author chenLiuPing
 **/
@Service
@Slf4j
public class TrackClient {

    @Value("${map.key}")
    private String key;

    @Value(("${map.sid}"))
    private String sid;

    @Autowired
    private RestTemplate restTemplate;

    public ResponseResult add(String tid) {
        log.info("sid:{}", sid);
        log.info("tid:{}", tid);
        // 拼接请求url
        StringBuilder url = new StringBuilder(MapConfigConstants.TRACK_ADD);
        url.append("?key=").append(key);
        url.append("&sid=").append(sid);
        url.append("&tid=").append(tid);
        log.info("url:{}", url);
        ResponseEntity<String> forEntity = restTemplate.postForEntity(url.toString(), null, String.class);
        String body = forEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        JSONObject data = jsonObject.getJSONObject("data");
        String trid = data.getString("trid");
        String trname = "";
        if (data.containsKey("trname")) {
            trname = data.getString("trname");
        }
        TrackResponse trackResponse = new TrackResponse(trid, trname);
        return ResponseResult.success(trackResponse);
    }
}
